package com.tuo51.manager.controller;


import com.google.common.collect.ImmutableMap;
import com.tuo51.core.domain.org.Organization;
import com.tuo51.core.domain.staffs.Staff;
import com.tuo51.core.repositories.OrgnizationRepository;
import com.tuo51.core.repositories.StaffRepository;
import com.tuo51.core.service.StaffService;
import com.tuo51.foudation.constant.CommonConstant;
import com.tuo51.foudation.exception.BusinessException;
import com.tuo51.foudation.model.ErrorCode;
import com.tuo51.foudation.model.MemVerificationCache;
import com.tuo51.foudation.model.StatusResponse;
import com.tuo51.foudation.utils.CopyUtils;
import com.tuo51.manager.vo.OrganizationEditVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

import static com.tuo51.foudation.constant.RequestConstant.TICKET;
import static org.springframework.web.bind.annotation.RequestMethod.GET;

/**
 * 附近的合作伙伴
 */
@RestController
@RequestMapping("/mapi/orgs")
@Api(value = "/mapi/orgs", tags = "OP - 机构管理")
public class MAPIOrgnizationController {

    @Autowired
    OrgnizationRepository orgRepository;

    @Autowired
    MemVerificationCache cache;

    @Autowired
    StaffService staffService;

    @Autowired
    StaffRepository staffRepository;

    @RequestMapping(value = "/list", method = GET)
    @ApiOperation(value = "查询机构列表")
    public StatusResponse orglist(@RequestHeader(TICKET) String ticket,
                                  @RequestParam(value = "pageNum", required = false, defaultValue = "0")Integer pageNum,
                                  @RequestParam(value = "pageSize", required = false, defaultValue = "15")Integer pageSize,
                                   @RequestParam(value = "searchBy", required = false) String searchBy){

        String staffId = cache.getStaffId(ticket);

        PageRequest pager = PageRequest.of(pageNum, pageSize);

        if (StringUtils.isEmpty(searchBy)){
            return StatusResponse.success(orgRepository.findAllByContactNumberIsNotNullAndBizOrgIsTrueOrderByCreatedDesc(pager));
        }

        return StatusResponse.success(orgRepository.findAllByNameLikeAndContactNumberIsNotNullAndBizOrgIsTrueOrderByCreatedDesc(searchBy, pager));
    }


    //TODO :下面的代码都要移到service层

    @RequestMapping(value = "/info", method = GET)
    @ApiOperation(value = "机构详情")
    public StatusResponse orginfo(@RequestHeader(TICKET) String ticket,
                                   @RequestParam(value = "orgId", required = true)String orgId){

        String staffId = cache.getStaffId(ticket);


        Organization org = orgRepository.getOne(orgId);

        List staffs = staffRepository.findAllByOrgIdAndPlatform(org.getId(), CommonConstant.Platform.WXMA.codeOf());

        Map ret = ImmutableMap.of("org", org, "members", staffs);

        return StatusResponse.success(ret);
    }

    @RequestMapping(value = "/edit", method = GET)
    @ApiOperation(value = "机构详情编辑")
    public StatusResponse editOrg(@RequestHeader(TICKET) String ticket,
                                  OrganizationEditVO org){

        String staffId = cache.getStaffId(ticket);

        Organization ret = null;
        if (StringUtils.isNotEmpty(org.getId())){
            ret = orgRepository.getOne(org.getId());
        }
        if (ret == null){
            throw new BusinessException(ErrorCode.MATERIAL_NOT_EXIST, "条目不存在");
        }

        ret.setTest(org.getTest());

        ret.setLogo(org.getLogo());
        ret.setExpireTime(org.getExpireTime());

        ret.setName(org.getName());
        ret.setContactNumber(org.getContactNumber());
        ret.setAddress(org.getAddress());

        ret.setPcaCode(org.getPcaCode());
        ret.setPcaCodeDesc(org.getPcaCodeDesc());

        ret.setRestCount(org.getRestCount());
        ret.setCode(org.getCode());

        ret.setStaffQuota(org.getStaffQuota());

        if (org.getBizOrg()) {
            ret.setBizOrg(true);
        }

        orgRepository.save(ret);

        return StatusResponse.success();
    }

    @RequestMapping(value = "/bizorg_trans", method = GET)
    @ApiOperation(value = "转换成商业机构")
    public StatusResponse transBiz(@RequestHeader(TICKET) String ticket,
                                   String orgId){

        String staffId = cache.getStaffId(ticket);

        Organization ret = orgRepository.getOne(orgId);

        if (ret == null || ret.getBizOrg()){
            throw new BusinessException(ErrorCode.VERSION_ERROR, "不是合适的机构");
        }

        //创建商业机构对象
        Organization bizOrg = new Organization();

        //复制商业机构对象授权
        CopyUtils.copyProperties(ret, bizOrg);

        //商业机构配置
        bizOrg.setId(null);
        bizOrg.setBizOrg(true);

        //清理自己机构的授权
        ret.setExpireTime(null);

        //保存
        orgRepository.save(ret);
        orgRepository.save(bizOrg);

        //管理员配置更新
        Staff staff = staffRepository.getOne(ret.getCreatorId());
        staff.setOrgId(bizOrg.getId());
        staffRepository.save(staff);

        return StatusResponse.success();
    }

    @RequestMapping(value = "/bizorg_set_admin", method = GET)
    @ApiOperation(value = "商业机构设置管理员")
    public StatusResponse setAdminBiz(@RequestHeader(TICKET) String ticket,
                                      String orgId, String staffId){

        String csid = cache.getStaffId(ticket);

        Organization ret = orgRepository.getOne(orgId);

        if (ret == null || !ret.getBizOrg() ){
            throw new BusinessException(ErrorCode.MATERIAL_NOT_EXIST, "商业机构不存在");
        }

        Staff staff = staffRepository.getOne(staffId);
        if (ret == null ){
            throw new BusinessException(ErrorCode.STAFF_NOT_EXIST, "用户不存在");
        }

        ret.setAdminId(staffId);
        orgRepository.save(ret);

        return StatusResponse.success(staff);
    }

    @RequestMapping(value = "/bizorg_add", method = GET)
    @ApiOperation(value = "商业机构增加成员")
    public StatusResponse addStaffBiz(@RequestHeader(TICKET) String ticket,
                                   String orgId, String staffId){

        String csid = cache.getStaffId(ticket);

        Organization ret = orgRepository.getOne(orgId);

        if (ret == null || !ret.getBizOrg() ){
            throw new BusinessException(ErrorCode.MATERIAL_NOT_EXIST, "商业机构不存在");
        }

        if (ret.getStaffCount() == ret.getStaffQuota()){
            throw new BusinessException(ErrorCode.MATERIAL_NOT_EXIST, "商业机构成员配额不够");
        }

        Staff staff = staffRepository.getOne(staffId);
        if (ret == null ){
            throw new BusinessException(ErrorCode.STAFF_NOT_EXIST, "用户不存在");
        }

        ret.setStaffCount(ret.getStaffCount() + 1);
        orgRepository.save(ret);

        staff.setOrgId(orgId);
        staffRepository.save(staff);

        return StatusResponse.success(staff);
    }

    @RequestMapping(value = "/bizorg_remove", method = GET)
    @ApiOperation(value = "商业机构移除成员")
    public StatusResponse removeStaffBiz(@RequestHeader(TICKET) String ticket,
                                      String orgId, String staffId){

        String csid = cache.getStaffId(ticket);

        Organization ret = orgRepository.getOne(orgId);

        if (ret == null || !ret.getBizOrg() ){
            throw new BusinessException(ErrorCode.MATERIAL_NOT_EXIST, "商业机构不存在");
        }

        if (ret.getStaffCount() == 0){
            throw new BusinessException(ErrorCode.MATERIAL_NOT_EXIST, "商业机构成员数量不够");
        }


        Staff staff = staffRepository.getOne(staffId);
        if (ret == null ){
            throw new BusinessException(ErrorCode.STAFF_NOT_EXIST, "用户不存在");
        }

        ret.setStaffCount(ret.getStaffCount() - 1);
        orgRepository.save(ret);

        staff.setOrgId(null);
        staffRepository.save(staff);

        return StatusResponse.success(staff);
    }


}
